package com.linkstec.mongo;

import java.net.UnknownHostException;
import java.util.HashSet;
import java.util.Set;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
  
public class MongoTestNew {
	private static final Logger logger = LoggerFactory.getLogger(MongoTestNew.class);
  
    public static void main(String[] args) throws UnknownHostException {  
          
        /** 
         * Mongo类代表与MongoDB服务器的连接，有多种构造函数。无参构造函数默认连接localhost:27017. 
         */  
    	MongoClient mongoClient = new MongoClient("localhost:27017");  
        /** 
         * DB类代表数据库，如果当前服务器上没有该数据库，会默认创建一个 
         */  
    	MongoDatabase db = mongoClient.getDatabase("MOT");  
        /** 
         * DBCollection代表集合，如果数据库中没有该集合，会默认创建一个 
         */  
    	MongoCollection<Document> users = db.getCollection("users");
        /** 
         * DBObject代表文档，这是一个接口，java中提供了多种实现，最简单的就是BasicDBObject了 
         */  
    	for (int i = 0; i < 100; i++) {
    		Document user = new Document();
    		
    		user.put("name", "jimmy");
    		user.put("age", "34" + i);
    		user.put("工作", "程序员");
    		Document address = new Document();
    		address.put("city", "bj");
    		address.put("street", "bq road");
    		address.put("mail", "ufpark 68#");
    		/**
    		 * 对于内嵌文档，我们需要先将内嵌文档填充后，再填充到外层文档中
    		 */
    		user.put("address", address);
    	}
    	// 将该文档插入到集合中
//    	users.insertOne(user);
        // 从集合中查询数据，我们就查询一条，调用findOne即可
        /*long count = users.count(Filters.eq("age", "341"));
        logger.info(Long.toString(count));
        for (Document documentOne : users.find(Filters.eq("age", "34"))) {
        	System.out.println(documentOne);
        	
        }*/
    	Set<String> ageSet = new HashSet<String>();
    	ageSet.add("340");
    	ageSet.add("341");
    	
        for (Document document : users.find(Filters.in("age", ageSet)).sort(Sorts.descending("age"))) {
            System.out.println(document);
        }
        /*long start3 = System.currentTimeMillis();
        for (int i = 0; i <= 100000; i++){
        	users.find(Filters.in("age", ageSet));
        }

        long end3 = System.currentTimeMillis();
        logger.info((end3 - start3) +"end3");*/
//        mongoClient.close();
        /*try {
			Thread.sleep(600000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}*/
        logger.info("" + users.countDocuments());
        /*long start = System.currentTimeMillis();
        for (int i = 0; i <= 10000; i++){
        	users = db.getCollection("users");
        	users.count();
        }

        long end = System.currentTimeMillis();
        logger.info((end - start) +"end");*/
		MongoCollection<Document> motEventRepeat = db.getCollection("MOT_EVENT_REPEAT_test2");
        // 10秒自动删除
//		IndexOptions indexOptions = new IndexOptions().expireAfter(100L, TimeUnit.SECONDS);
//        motEventRepeat.createIndex(Indexes.ascending("lastTime"), indexOptions);
        
        /*UpdateOptions updateOptions = new UpdateOptions();
		updateOptions.upsert(true);
		UpdateResult updateResult = null;
		long start2 = System.currentTimeMillis();
		for (int i = 0; i <= 10; i++){
			
			updateResult = motEventRepeat.updateOne(
					Filters.and(
							Filters.eq("event_id", "382"),
							Filters.eq("customer_id", "12345678")),
					Updates.combine(
							Updates.setOnInsert("event_id", "382"),
							Updates.setOnInsert("customer_id", "12345678"),
							Updates.addToSet("setset", "12345678" + i),
							Updates.setOnInsert("intTest", 0),
							Updates.setOnInsert("lastTime", new Date())),
					updateOptions);
		}
        long end2 = System.currentTimeMillis();
        logger.info((end2 - start2) +"end2");
        logger.info(updateResult.getMatchedCount() + "");*/
        // 取出查看
        FindIterable<Document> iterable = motEventRepeat.find();
        MongoCursor<Document> mongoCursor = iterable.iterator();
        while (mongoCursor.hasNext()){
        	Document EventRepeat = mongoCursor.next();
        	logger.info(EventRepeat.toJson());
        	// 日期类型自动转化了
//        	logger.info(EventRepeat.getDate("lastTime").toString());
//        	logger.info(EventRepeat.get("intTest").toString());
//            Integer intTest = Integer.parseInt(EventRepeat.get("intTest").toString());
        }
        
//        long start = System.currentTimeMillis();
        /*Document document = null;
		for (int i = 0; i <= 10000; i++){
//			user.put("_id", i);
//			motEventRepeat.insertOne(user);
			document = motEventRepeat.findOneAndUpdate(
					Filters.and(
//							Filters.eq("event_id", "382")), Updates.combine(
							Filters.eq("_id", "382")), Updates.combine(
									Updates.set("customer_id", "12345678")));
		}
		long end = System.currentTimeMillis();
        logger.info((end - start) +"");
        if (null == document) {
        	logger.info("document为null");
        } else {
        	logger.info("document不为null");
        }*/
		/*UpdateResult updateResult = motEventRepeat.updateOne(
				Filters.and(
				    Filters.eq("custId", "12345678"),
				    Filters.exists("firstCashIn", false)),
				Updates.combine(
						Updates.set("custId", "12345678"),
						Updates.set("firstCashIn", "0"),
						Updates.set("lastTime", new Date())),
				updateOptions);
		UpdateResult updateResult2 = motEventRepeat.updateOne(
				Filters.and(
						Filters.eq("custId", "12345678"),
						Filters.exists("firstDeal", false)),
				Updates.combine(
						Updates.set("custId", "12345678"),
						Updates.set("firstDeal", "0"),
						Updates.set("lastTime", new Date())),
				updateOptions);
		UpdateResult updateResult2 = motEventRepeat.updateOne(
				Filters.and(
						Filters.eq("custId", "12345678")),
				Updates.combine(
						Updates.set("custId", "12345678"),
						Updates.set("firstDeal", "2"),
						Updates.set("intTest", 0),
						Updates.setOnInsert("lastTime", new Date())),
				updateOptions);*/
        mongoClient.close(); 
    }
}